<template>
    <div class="history-list" @click="doHide()">
        <h3 @click.stop>历史记录</h3>
        <ul @click.stop>
            <li @click="doSwitchTopic(item)" v-for="(item, index) in listDatas" :key="item.id">{{ item.title }}<i class="iconfont" @click="doDelete(index)">&#xe659;</i></li>
        </ul>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue'
export default {
    setup (props, { emit }) {
        const listDatas = ref([])
        const refresh = () => {
            let historyDatas = localStorage.getItem('AiHistoryChatDatas')
            if (historyDatas) {
                historyDatas = JSON.parse(historyDatas)
                if (historyDatas.length > 0) {
                    listDatas.value = historyDatas
                }
            }
        }

        const doHide = () => {
            document.querySelector('.history-list')?.classList.remove('show')
        }

        const doSwitchTopic = (item) => {
            emit('switchtopic', item.id)
            doHide()
        }

        const doDelete = (index) => {
            listDatas.value.splice(index, 1)
            setTimeout(() => {
                localStorage.setItem('AiHistoryChatDatas', JSON.stringify(listDatas.value))
            }, 100)
        }

        onMounted(() => {
            refresh()
        })

        return {
            listDatas,
            refresh,
            doSwitchTopic,
            doHide,
            doDelete
        }
    }
}
</script>

<style lang="scss">
    @use './style.scss';
</style>
